#                                                   #								
# bash functions and parameters                     #
# At Consulting (c)                                 #
# MMartynov@vrn.beeline.ru                          #
#                                                   #
#                                                   #

source $HOME/.profile &>/dev/null

##########################################################
# CHECK ENVIRONMENT
##########################################################

if [ -z "$OPENARS_HOME" ]; then
    echo "please, define and export OPENARS_HOME in your .progile. exit 1." >&2
    exit 1
fi

if [ ! -d "$OPENARS_HOME" ]; then
    echo "not find OPENARS_HOME directory: $OPENARS_HOME. exit 1." >&2
    exit 1
fi

##########################################################
# INITIALIZATION AND PRIVATE FUNCTIONS
##########################################################

[ -z "$_INCLUDE_CONF" ] && source $OPENARS_HOME/common/conf.h
main_setenv

#use: "set $SQL_PARAM" for sqlplus
SQL_PARAM="PAGESIZE 0   \
           ECHO OFF     \
           FEEDBACK OFF \
           HEADING OFF  \
           TERMOUT OFF  \
           VERIFY OFF
           WHENEVER SQLERROR EXIT SQL.SQLCODE"

##########################################################
# PUBLIC FUNCTIONS
##########################################################

# use: question <text> <varname_result>
function question() {
[ "$#" -lt 2 ] && return 1
text="$1"
flag="unknown"
while [ "$flag" != "Y" -a "$flag" != "N" ]
do
    echo -ne "\t$text [Y/N] "
    read flag
    case $flag in
    "Y"|"y")	flag="Y"
		;;
    "N"|"n")	flag="N"
		;;
    esac						     
done			
[ ! -z "$2" ] && eval $2="\"$flag\""
return 0    
} 

function get_hosts() {
    optname=()
    optvalue=()
    i=1
    while [ $# -gt 0 ]
    do
	case "$1" in
	-*=*) optname[$i]=`echo "$1" | sed 's/=[-_a-zA-Z0-9]*//' | sed 's/^-*//'`
	      optvalue[$i]=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'`	
	      let "i += 1"
	      ;;
	esac
	shift
    done	

    if [ "$ORACLE_ENABLE" = "N" ]; then # use conf/hosts.xml
	mygrep="grep ."
	i=1
	while [ $i -le ${#optname[@]} ]
	do
	    mygrep="$mygrep | grep ${optname[$i]}=\\\"${optvalue[$i]}\\\""
	    let "i += 1"
	done
	format_host | eval $mygrep | get_xmlparam "host"
    else
	param="1=1"
	i=1
	while [ $i -le ${#optname[@]} ]
	do
	    param="$param and ${optname[$i]} = '${optvalue[$i]}'"
	    let "i += 1"
	done
	if [ -z "CONNECT_ARS" ]; then
	    echo "get_hosts(): not defined CONNECT_ARS environment for Oracle connect" >&2
	    return
	fi
	res=`$ORACLE_HOME/bin/sqlplus -s /NOLOG  <<END 
	    set PAGESIZE 0 ECHO OFF FEEDBACK OFF HEADING OFF TERMOUT OFF VERIFY OFF
	    WHENEVER SQLERROR EXIT SQL.SQLCODE
    	    connect $CONNECT_ARS
	    select host from hosts where $param;
	    exit;
	END`
	exit_code=$?
	if [ "$exit_code" -ne 0 ]; then
	    echo "get_hosts(): sqlplus ERROR: $res" >&2
	    res=""
	fi    
	echo "$res"
    fi
}
